<?php

receive_file();
function run()
{
	
	send_file('3.png');
}
function receive_file()
{
	$file_url = @$_POST['file'];
	$patch = @$_POST['patch'];
	$result = array();
	$result['error'] = 2;
	$result['msg'] = '';
	if($file_url && $patch)
	{
		$image_data = get_data($file_url);
		if($image_data)
		{
			$file_name = basename($patch);
			
			create_dirs('temp/');
			$temp_upload = './temp/'.$file_name;
			file_put_contents($temp_upload, $image_data);
			$info = mime_content_type($temp_upload);
			$type_allow = array(
				'image/jpeg',
				'image/pjpeg', 'image/pjpeg','image/png',
				'image/jpeg', 'image/pjpeg',
				'image/png',  'image/x-png',
				'image/bmp', 'image/x-windows-bmp'
			);
			if(in_array($info, $type_allow))
			{
				create_dirs($patch);
				rename($temp_upload, $patch);
				$result['error'] = 0;
				$result['msg'] = 'Trans file to '.$patch.' ok';
			}
			else
			{
				$result['error'] = 1;
				$result['msg'] = 'Image type not allow';
				//put_time('file-'.$temp_upload,time(), time());
				@unlink($temp_upload);
			}
			
		}
	}
	die(json_encode($result));
}

function send_file($file_patch = '')
{
	$result = array();
	$data = array();
	$result['patch'] = $file_patch;
	$result['file'] = 'http://localhost:9090/vui.us/'.$file_patch;
	$webservices = array(
			'http://localhost:9090/vui.us/transfer.php',
		 );
	foreach($webservices as $webservice)
	{
		$data[] = post_data($webservice, $result);
	}
	return $data;
}

function post_data($url, $form_data ,$ref_url='',$arr_header= array())
{
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	if(count($arr_header)>0)
	curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	if($ref_url !='')
	curl_setopt($ch, CURLOPT_REFERER, $ref_url);
	
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);
	
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

function get_data($url, $ref_url='')
{
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	if($ref_url !='')
	curl_setopt($ch, CURLOPT_REFERER, $ref_url);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}
function create_dirs($file =''){
	$dir_paths = explode("/",$file);
	$dir = "";
	for($i=0; $i<count($dir_paths) -1; $i++){
		$dir_path = $dir_paths[$i];
		$dir.= $dir_path."/";
		if (!is_dir($dir)) {
			mkdir($dir);
			chmod($dir, 0777);
		}
	}
	return $dir;
}
